
package com.eshop.common.interceptor;


import com.eshop.api.ApiCode;
import com.eshop.api.UnAuthenticatedException;
import com.eshop.common.bean.LocalUser;
import com.eshop.common.util.JwtToken;
import com.eshop.constant.ShopConstants;
import com.eshop.modules.user.domain.ShopUser;
import com.eshop.modules.user.service.UserService;
import com.eshop.utils.RedisUtils;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Optional;

/**
 * 权限拦截器
 * @author zhonghui
 * @date 2020-04-30
 */
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    public PermissionInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //因为是拦截器，所以所有接口都拦截，但不是所有的接口都加了@AuthCheck注解，因此这里检测该方法是否有该注解
        Optional<AuthCheck> authCheck = this.getAuthCheck(handler);
        //如果没有该注解就直接放行了
        if (!authCheck.isPresent()) {
            return true;
        }

        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.isEmpty(bearerToken)) {
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }

        if (!bearerToken.startsWith("Bearer")) {
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        String[] tokens = bearerToken.split(" ");
        if (!(tokens.length == 2)) {
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        String token = tokens[1];
        //获取出token
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        Map<String, Claim> map = optionalMap
                .orElseThrow(() -> new UnAuthenticatedException(ApiCode.UNAUTHORIZED));

        String uName = map.get("uName").asString();

        //检测用户是否被踢出 uName实际上就是userName，userName实际上存的就是手机号
        if (redisUtils.get(ShopConstants.YSHOP_APP_LOGIN_USER + uName + ":" + token) == null) {
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        //authCheck.get()传过去的就是一个注解
        boolean valid = this.hasPermission(authCheck.get(), map);
        //如果通过权限校验，就可以存到ThreadLocal里面
        if(valid){
            this.setToThreadLocal(map);
        }
        //妙啊，这里顺便返回的valid，如果valid为true就刚好放行了，如果为false就不放行
        return valid;
    }

    //存数据到ThreadLocal里面，这里面很细的就是scope，这个scope是一开始在JwtToken里面定义了一个默认值
    //就是登录的用户默认scope就是8，因此这里实际上是没有加权限校验的，后期可以拓展
    private void setToThreadLocal(Map<String,Claim> map) {
        Integer uid = map.get("uid").asInt();
        //scope默认为8
        Integer scope = map.get("scope").asInt();
        ShopUser user = userService.getById(uid);
        if(user == null) {
            throw new UnAuthenticatedException(ApiCode.NOT_PERMISSION);
        }
        LocalUser.set(user, scope);
    }

    //权限校验，类似七月的@ScopeLevel
    private boolean hasPermission(AuthCheck authCheck, Map<String, Claim> map) {
        //注解上的value就是访问该接口需要的权限级别
        Integer level = authCheck.value();
        //scope默认为8
        Integer scope = map.get("scope").asInt();
        if (level > scope) {
            throw new UnAuthenticatedException(ApiCode.NOT_PERMISSION);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //接口方法执行完就清除LocalUser
        LocalUser.clear();
        super.afterCompletion(request, response, handler, ex);
    }

    private Optional<AuthCheck> getAuthCheck(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AuthCheck authCheck = handlerMethod.getMethod().getAnnotation(AuthCheck.class);
            if (authCheck == null) {
                return Optional.empty();
            }
            return Optional.of(authCheck);
        }
        return Optional.empty();
    }

}
